var SELECTGRID;
var columns = [{
    checkbox: true
}, {
    field: 'id',
    title: '序号',
    formatter: function (value, row, index) {
        return index + 1;
    }
},
    {
        field: 'sheet',
        title: '图幅号'
    }, {
        field: 'scale',
        title: '比例尺'
    }, {
        field: 'type',
        title: '种类'
    }, {
        field: 'num',
        title: '数量',
        align: 'center'
    }, {
        field: 'name',
        title: '图名'
    }, {
        field: 'location',
        title: '位置'
    }, {
        field: 'year',
        title: '年代'
    }, {
        field: 'result',
        title: '结果'
    }, {
        field: 'operator',
        title: '操作',
        formatter: actionFormatter
    },];

var option = {
    url: "http://localhost:8888/paper/map/inventory/table/list",         //请求后台的URL（*）
    method: 'post',                      //请求方式（*）
    dataType: 'json',
    toolbar: '#toolbar',                //工具按钮用哪个容器
    theadClasses: '.thead-light',
    striped: true,                      //是否显示行间隔色
    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
    pagination: true,                   //是否显示分页（*）
    showPaginationSwitch: false,        //是否显示分页数
    sortable: true,                     //是否启用排序
    // sortName: "title",                     //是否启用排序
    sortOrder: "desc",                   //排序方式
    queryParams: function (params) {
        // 特别说明：
        //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
        // 如果queryParamsType=limit,params包含{limit, offset, search, sort, order}
        // 如果queryParamsType!=limit,params包含{pageSize, pageNumber, searchText, sortName, sortOrder}
        var temp = {
            fieldName: 'scale',
            value: 5,
        };
        return temp;
    },//传递参数（*）
    queryParamsType: '',                //如果要在oTableInit.queryParams方法获取pageNumber和pageSize的值，需要将此值设置为空字符串（*）
    sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
    pageNumber: 1,                       //初始化加载第一页，默认第一页
    pageSize: 25,                       //每页的记录行数（*）
    pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
    contentType: "application/x-www-form-urlencoded;charset=UTF-8",
    search: true,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
    strictSearch: true,
    showColumns: true,                  //是否显示所有的列
    showRefresh: true,                  //是否显示刷新按钮
    minimumCountColumns: 2,             //最少允许的列数
    clickToSelect: true,                //是否启用点击选中行
    singleSelect: false,                 //是否单选模式
    height: $(window).height() - 200,   //table总高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
    uniqueId: "id",                     //每一行的唯一标识，一般为主键列
    showToggle: true,                    //是否显示详细视图和列表视图的切换按钮
    cardView: false,                    //是否显示详细视图
    detailView: false,                   //
    maintainSelected: true,
    paginationPreText: "上一页",
    paginationNextText: "下一页",
    columns: columns,
    onLoadSuccess: function (result) {  //加载成功时执行
        console.info("加载成功");
    },
    onLoadError: function (result) {  //加载失败时执行
        console.info("加载数据失败");
    },
    //双击单元格修改数据
    onClickCell: function (field, value, row, $element) {
        if (field != "operator" && field != "id" && field != "result") {
            $element.attr('contenteditable', true);
            $element.blur(function () {
                let index = $element.parent().data('index');
                let tdValue = $element.html();
                $('#table').bootstrapTable('updateCell', {
                    index: index,
                    field: field,
                    value: tdValue
                })
            })
        }
    }

}

$(function () {

    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();

    var newdata = {id: 1, sheet: "01-41", scale: 100, type: 0, num: 520, name: "", location: 1, year: ""};
    $('#table').bootstrapTable('append', newdata);

});


var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#table').bootstrapTable(option);
    };

    return oTableInit;
};


var ButtonInit = function () {
    var oInit = new Object();
    var postdata = {};

    oInit.Init = function () {
        //增加一行数据
        $("#btn_add").click(function () {
            var dataList = $("#table").bootstrapTable("getData", true);
            console.info(dataList)
            var _id = dataList.length + 1;
            var newdata = {id: _id, sheet: "", scale: "", type: 0, num: 0, location: 1, year: "",}
            $('#table').bootstrapTable('append', newdata);
        });

        //导入EXCEL按钮事件
        document.querySelector("#btn_import").addEventListener("change", function () {
            var leng = $('#table').bootstrapTable('getData', {useCurrentPage: false, includeHiddenRows: false}).length;
            //获取到选中的文件
            var file = document.querySelector("#btn_import").files[0];
            var type = file.name.split('.');
            if (type[type.length - 1] !== 'xlsx' && type[type.length - 1] !== 'xls') {
                alert('只能选择excel文件导入');
                return false;
            }
            const reader = new FileReader();
            reader.readAsBinaryString(file);
            reader.onload = (e) => {
                const data = e.target.result;
                const zzexcel = window.XLS.read(data, {
                    type: 'binary'
                });
                const result = [];
                for (let i = 0; i < zzexcel.SheetNames.length; i++) {
                    const newData = window.XLS.utils.sheet_to_json(zzexcel.Sheets[zzexcel.SheetNames[i]]);
                    for (var j = 0; j < newData.length; j++) {
                        var deal_data = Excel_Deal(newData[j]);
                        //获取包含分页的全部数据，但是不包含隐藏行的数据
                        leng++;
                        deal_data.id = leng;
                        result.push(deal_data);
                    }
                }
                $('#table').bootstrapTable('append', result);
                console.log('result', result)
            }
            document.getElementById("btn_import").value = ""
        });

        //导入按钮事件
        $("#btn_edit").click(function () {
            $("#btn_import").click();
        });

        //删除按钮事件
        $("#btn_delete").click(function () {
            var obj = $('#table');
            var ids = $.map(obj.bootstrapTable('getSelections'), function (row) {
                return row.id
            });

            obj.bootstrapTable('remove', {field: 'id', values: ids});
        });

        //清空按钮事件
        $("#btn_clear").click(function () {
            //删除表格所有数据
            $('#table').bootstrapTable('removeAll');
            $('#table').bootstrapTable('refresh');
        });


        //提交到数据库
        $("#btn_submit").click(function () {
            var ids = [];
            var rows = $.map($('#table').bootstrapTable('getSelections'), function (row, index) {
                ids.push(index)
                console.info("index", index)
                return row
            });

            var data = [];
            var log = [];

            var identifier = getIdentifier()
            var event_now = {
                "identifier": identifier,
                "date": getDateTime(),
                "event": "add",
                "type": 0,
                "num": 0,
                "sheetNum": rows.length,
                "size": 0,
                "organization": "自然资源局",
                "person": "刘先生",
                "tel": "18888888888"
            };
            var num = 0;
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i]
                if (row.result == "成功")
                    continue;
                var data1 = {
                    "sheet": row.sheet,
                    "scale": row.scale,
                    "type": row.type,
                    "num": row.num,
                    "location": row.location,
                    "year": row.year
                }
                var data_log = {
                    "sheet": row.sheet,
                    "scale": row.scale,
                    "type": row.type,
                    "num": row.num,
                    "location": row.location,
                    "year": row.year,
                    "identifier": identifier,
                    "operator": "add",
                }
                num += parseInt(row.num);
                data.push(data1);
                log.push(data_log)
            }
            event_now.num = num;
            // //提交数据
            // $.ajax({
            //     type: "post",
            //     url: "http://localhost:8888/paper/map/inventory/table/mapReceive",
            //     data: JSON.stringify(data),
            //     contentType: "application/json",
            //     success: function (result) {
            //         if (result.message == "SUCCESS") {
            //             for (var i = 0; i < result.data.length; i++) {
            //                 var sss;
            //                 if (result.data[i])
            //                     sss = "成功";
            //                 $('#table').bootstrapTable('updateCell', {
            //                     index: ids[i],
            //                     field: 'result',
            //                     value: sss
            //                 })
            //             }
            //         }
            //     },
            //     error: function (re) {
            //         // toastr.error('Error');
            //     },
            //     complete: function () {
            //
            //     }
            // });
            //提交操作
            $.ajax({
                type: "post",
                url: "http://localhost:8888/operator/data/log/table/addLog",
                data: JSON.stringify(log),
                contentType: "application/json",
                success: function (result) {
                    if (result.message == "SUCCESS") {
                        console.info("log", "sucess");
                    }
                },
                error: function (re) {
                    // toastr.error('Error');
                },
                complete: function () {

                }
            });
            //提交事件

            //提交操作
            $.ajax({
                type: "post",
                url: "http://localhost:8888/event/log/add",
                data: JSON.stringify(event_now),
                contentType: "application/json",
                success: function (result) {
                    if (result.message == "SUCCESS") {
                        console.info("event", "sucess");
                    }
                },
                error: function (re) {
                    // toastr.error('Error');
                },
                complete: function () {

                }
            });
        });

        //list
        $("#btn_query").click(function () {
            var new_url = "http://localhost:8888/paper/map/inventory/table/list_table";
            $("#table").bootstrapTable('refresh', {url: new_url});
        });

        //接图表导入
        $("#btn_grid").click(function () {
            ol.Observable.unByKey(db_click);
            $("#ReceivePlan").modal("toggle");
            $("#myTabs li:eq(0) a").tab('show');
            current_mode = 1;
            Toast("选择图幅", 1000);
            selectedSheet = [];


            //鼠标单击事件
            SELECTGRID = map.on("click", function (e) {
                menu_overlay.setPosition(undefined);

                rectangleSource = new ol.source.Vector();
                map.removeLayer(SelectSheetLayer);
                var coor = ol.proj.transform(e.coordinate, "EPSG:3857", "EPSG:4326");
                coor = [coor[0].toFixed(6), coor[1].toFixed(6)];
                var sheet = LngLat2Sheet(coor, select_scale);
                var compare = selectedSheet.indexOf(sheet)
                if (compare == -1) {
                    selectedSheet.push(sheet);
                } else {
                    selectedSheet.remove(sheet);
                }
                console.info("selectedSheet", selectedSheet);
                for (var i = 0; i < selectedSheet.length; i++) {
                    addRectangular(selectedSheet[i], getLnglat_step(select_scale), "rgb(187,100,100,0.8)", select_scale, SelectSheetLayer);
                }
                SelectSheetLayer.setSource(rectangleSource);
                SelectSheetLayer.setZIndex(11);
                map.addLayer(SelectSheetLayer);
                document.getElementById("selectBar").innerText = "已选择" + selectedSheet.length + "幅图";
            })


            //鼠标右键点击事件
            $(map.getViewport()).on("contextmenu", function (e) {
                //取消默认注释
                e.preventDefault(e);
                // 书写事件触发后的函数
                var coordinate = map.getEventCoordinate(e);
                menu_overlay.setPosition(coordinate);
            });
        });

        //测试按钮
        $("#btn_test").click(function () {
            $('#table').bootstrapTable('updateCell', {
                index: 0,
                field: 'result',
                value: "成功"
            })
        });
    };

    return oInit;
};


//操作栏的格式化
function actionFormatter(value, row, index) {
    var id = row.id;
    var result = "";
    result += "<a href='javascript:;' class='btn btn-xs green' onclick=\"EditViewById('" + id + "', view='view')\" title='查看'><span class='glyphicon glyphicon-search'></span></a>";
    // result += "<a href='javascript:;' class='btn btn-xs blue' onclick=\"EditViewById('" + id + "')\" title='编辑'><span class='glyphicon glyphicon-pencil'></span></a>";
    result += "<a href='javascript:;' class='btn btn-xs red' onclick=\"DeleteByIds('" + id + "')\" title='删除'><span class='glyphicon glyphicon-remove'></span></a>";
    return result;
}

function DeleteByIds(id) {
    //根据Id字段删除对应的数据
    $('#table').bootstrapTable('removeByUniqueId', id);
}


//提交表单
function btn_ok() {
    $("#editPlan").modal("toggle");
    params.scale = document.getElementById("inputScale").value;
    params.type = document.getElementById("inputType").value;
    params.num = document.getElementById("inputNum").value;
    params.location = document.getElementById("inputLocation").value;
    params.year = document.getElementById("inputYear").value;
    menu_overlay.setPosition(undefined);
}

//测试
$("#recieve").click(function () {
    $("#table").bootstrapTable('refresh');
})

var params = {scale: "", type: "", num: "", name: "", location: "", year: ""};

//添加图幅
function back() {
    $("#ReceivePlan").modal("toggle");
    for (var i = 0; i < selectedSheet.length; i++) {
        var dataList = $("#table").bootstrapTable("getData", true);
        var _id = dataList.length + 1;
        var newdata = {
            id: _id,
            sheet: selectedSheet[i],
            scale: params.scale,
            type: params.type,
            num: params.num,
            location: params.location,
            year: params.year
        }
        $('#table').bootstrapTable('append', newdata);
    }
    current_mode = 0;
}

//批量设置参数
function setParams() {
    menu_overlay.setPosition(undefined);
    $("#editPlan").modal('toggle');
}

function endSelect() {
    map.on("dblclick", function (e) {
        var coor = ol.proj.transform(e.coordinate, "EPSG:3857", "EPSG:4326");
        coor = [coor[0].toFixed(6), coor[1].toFixed(6)];
        var sheet = LngLat2Sheet(coor, select_scale);
        searchBySheet(sheet);
    });
    ol.Observable.unByKey(SELECTGRID);
    select_type = 0;
    menu_overlay.setPosition(undefined);
}

//提交图幅号到表格
function addSheet2Table() {
    $("#ReceivePlan").modal("toggle");
    for (var i = 0; i < selectedSheet.length; i++) {
        var dataList = $("#table").bootstrapTable("getData", true);
        var _id = dataList.length + 1;
        var newdata = {
            id: _id,
            sheet: selectedSheet[i],
            scale: params.scale,
            type: params.type,
            num: params.num,
            location: params.location,
            year: params.year
        }
        $('#table').bootstrapTable('append', newdata);
    }
    current_mode = 0;
}


//数组移除元素
Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};


function getIdentifier() {
    return "test"
}

function getDateTime() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var Hours = date.getHours();
    var Minutes = date.getMinutes();
    var Seconds = date.getSeconds();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    // var s_createtime = year + '-' + month + '-' + day + ' ' + Hours + ':' + Minutes + ':' + Seconds;
    var s_createtime = year + '-' + month + '-' + day;
    return s_createtime;
}